import axios from 'axios';

import Oidc from "oidc-client";
// import router from '../traffic/router/index';
let oidc = process.env.OIDC;
let mgr = new Oidc.UserManager(oidc);




// 请求拦截器
axios.interceptors.request.use(async request => {
    //获取登录token
    const header = await mgr
        .getUser()
        .then(user => {
            // console.log(user);
            let headers = "Bearer " + user.access_token;
            return headers
        })
        .catch(e => {
            console.log(e);
        });


    //处理入参的数据（筛除前后空格）
    for (let i in request.data) {

        if (typeof(request.data[i]) == 'string') {
            request.data[i] = request.data[i].replace(/(^\s*)|(\s*$)/g, "")
        }

    }

    //修改头请求信息
    request.headers.Authorization = header
    request.headers['Content-Type'] = 'application/json; charset=utf-8';

    return request
}, error => {
    return Promise.reject(error);
})


//相应拦截器
axios.interceptors.response.use(response => {
    if (response.status === 200) {
        return Promise.resolve(response)
    } else {
        return Promise.reject(response)
    }
}, error => {
    console.log(error)
    if (error.response.status) {
        // console.log(error.response);
        switch (error.response.status) {
            case 400:
                // 可能是入参出错
                let errortab = {};
                let errormsg = error.response.data.errors;
                for (let x in errormsg) {
                    errortab[x] = errormsg[x][0]
                }
                let text = {
                    api: error.response.config.url,
                    json: error.response.config.data,
                    error: errortab
                }
                throw (text);
            case 401:
                mgr.signoutRedirect(); //登录
                throw ('401-未登录');
            case 405:
                throw ('405-ajax传送类型错误（get/post）');
            case 415:
                throw ('415-媒体类型(检查是否传参)');
            case 500:
                console.warn(error.response)
                throw ('500-服务器内部错');
        }
    }
})



export const Axios = (jsonobj, url, type) => { //调用接口时的顺序
    // export const Axios = (url, jsonobj, type) => { //调用mock时的顺序
    return new Promise(function(resolve, reject) {
        //进行ajax异步调用
        let promise

        if (type === 'get') {
            //传入对象形式
            let props = {
                params: jsonobj
            };
            promise = axios.get(url, props)
        } else {
            promise = axios({
                url: url,
                method: 'post',
                //发送格式为json
                data: jsonobj,
                dataType: "json"

            })
        }
        promise.then(function(response) {
            resolve(response.data)

        }).catch(function(error) {
            reject(error)
        })
    })
}